package com.aspirecn.order.config;

import java.util.Arrays;

import javax.servlet.http.HttpServletRequest;

import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import com.aspirecn.order.domain.ResultBean;


/**
 * @author chenyuanli
 */
@Aspect
@Configuration
public class ControllerAop {
	private static final Logger logger = LoggerFactory.getLogger(ControllerAop.class);

	@Pointcut("execution(public com.aspirecn.order.domain.ResultBean *(..))")
    public void excudeService(){}
	
	@Around("excudeService()")
	public Object handlerControllerMethod(ProceedingJoinPoint pjp) {
		long startTime = System.currentTimeMillis();
		ResultBean<?> result;
		try {
	        // 接收到请求，记录请求内容
	        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
	        HttpServletRequest request = attributes.getRequest();

	        // 记录下请求内容
	        logger.info("REQUEST URL : " + request.getRequestURL().toString());
	        logger.info("REQUEST HTTP METHOD : " + request.getMethod());
	        logger.info("REQUEST IP : " + request.getRemoteAddr());
	        logger.info("REQUEST CLASS_METHOD : " + pjp.getSignature().getDeclaringTypeName() + "." + pjp.getSignature().getName());
	        logger.info("REQUEST ARGS : " + Arrays.toString(pjp.getArgs()));
	        
			result = (ResultBean<?>) pjp.proceed();
		} catch (Throwable e) {
			result = handlerException(pjp, e);
		}
		
        // 处理完请求，返回内容
		logger.info("RESPONSE Code: " + result.getCode());
		logger.info("RESPONSE Msg: " + result.getMsg());
        logger.info("RESPONSE : " + result.getData());
        logger.info("RESPONSE : " + pjp.getSignature() + " SPEND TIME : " + (System.currentTimeMillis() - startTime));
		return result;
	}

	private ResultBean<?> handlerException(ProceedingJoinPoint pjp, Throwable e) {
		ResultBean<?> result = new ResultBean();
		logger.error(pjp.getSignature() + " error ", e);
		result.setMsg("系统异常，请联系管理员");
		result.setCode(ResultBean.FAIL);
		// TODO 未知异常如通知邮件，单独写到某个文件等等。
		return result;
	}
}
